import Vue from 'vue'
import Router from 'uni-simple-router'
import store from './store'
import {sldStatEvent,updateStatCommonProperty} from "./utils/stat.js";
import {WXBrowserShareThen} from './utils/common.js'
import {isWeiXinBrower} from './utils/base.js'
// #ifdef APP
import request from './utils/request.js'
// #endif
import diyStyle from './diyStyle'

// #ifdef MP-WEIXIN
const oldPush = Router.prototype.push
Router.prototype.push = function(arg){
    if(getCurrentPages()&&getCurrentPages().length>8){
        Router.prototype.replace.apply(this,[arg])
    }else{
        oldPush.apply(this,[arg])
    }        
}
// #endif

//#ifdef H5 ||MP-WEIXIN
const oldBack = Router.prototype.back
Router.prototype.back = function(arg){
    const pages = getCurrentPages()
    const prePage = pages[pages.length-2]
    if(prePage){
        oldBack.apply(this,[arg])
    }else{
        Router.prototype.pushTab.apply(this,['/pages/index/index'])
    }
}
// #endif

Vue.use(Router)
//初始化
const router = new Router({
	encodeURI: false, //默认为true
	routes: ROUTES //路由表
});
const setStyleBefore = diyStyle.getDiyStyleOnce()

//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
	//在前置守卫里调用，不然进入页面会出现颜色闪动的情况
	await setStyleBefore()
	if(to.meta&&to.meta.checkLogin){
		if(!store.state.hasLogin&&!uni.getStorageSync('userInfo')){
			let url = to.path;
			const query = to.query;
			uni.setStorageSync('fromurl', {url,query});
			next({path:'/pages/public/login'})
		}else{
			next();
		}
	}else{
		next();
	}
	
})
  //#ifdef APP
let timer = '1'
let getNetworkType_time = '';
let netNetworkFlag_time = '';
 //#endif
// 全局路由后置守卫
router.afterEach((to, from) => { 
	let url = getApp().globalData.apiUrl.substring(0, getApp().globalData.apiUrl.length - 1);
	//商品详情页、店铺的页面需要单独统计，但是需要把pageUrl和referrerPageUrl先存进去
	let specialPages = [
		'/pages/index/guidePage', //引导页
		'/standard/product/detail', //商品详情页
		'/standard/store/shopHomePage', //店铺首页
		'/standard/store/storeIntroduction', //店铺信息页
		'/standard/store/productSearch', //店铺商品列表页
		'/extra/tshou/goods/detail', //推手商品详情页
	];
  
	let statPvFlag = true;
	for (let i in specialPages) {
		if (specialPages[i].indexOf(to.path) > -1) {
			statPvFlag = false;
			break;
		}
	}
  //#ifdef APP
  let tabberRoute = [
  	'/pages/index/index',
  	'/pages/category/category',
  	'/pages/index/information',
  	'/pages/cart/cart',
  	'/pages/user/user',
  ];
  // 判断当前是否有网
  uni.getNetworkType({
  	success: function (res) {
      // networkType网络类型
      // res.networkType 的值 wifi 2g 3g 4g 5g ethernet(有线网络) unknown(Android 下不常见的网络类型) none(无网络)
      if(res.networkType=='none'){
        // 删除netNetworkFlag网络崩溃页点击刷新存储的标识
         uni.removeStorageSync('netNetworkFlag')
         // 在刚进入页面执行接口时判断是否是onshow和onload的参数
         uni.setStorageSync('configRoue',1)
         //调用清除configRoue本地缓存  防止返回上一页或进入没有请求接口的页面但事件调取接口不触发网络状态判断的情况
         request()
         //  执行赋值给getNetworkType_time的定时器前先销毁getNetworkType_time定时器
         clearTimeout(getNetworkType_time)
         // 使用定时器
         getNetworkType_time = setTimeout(()=>{
           const pages = getCurrentPages() //当前页面栈
           let routeNetwork = uni.getStorageSync('routeNetwork')||0 //获取存储的页面栈长度没有取0
           // tabber页面切换判断 判断是否是tabber页面并且判断是否有routeTabber本地存储并且判断是否是从tabber进入的网络崩溃页
           if(tabberRoute.join(',').indexOf(to.path)!=-1&&uni.getStorageSync('routeTabber')&&uni.getStorageSync('routeTabber')!=to.path){
             // 删除存储的页面栈长度
             uni.removeStorageSync('routeNetwork')
             // 进入网络崩溃页
             uni.navigateTo({
               url:'/standard/netNetwork/netNetwork'
             })  
             // 清除赋值给getNetworkType_time的定时器
             clearTimeout(getNetworkType_time)
             // 判断存储的页面栈长度是否存在 或者 存储的长度比实时页面栈的长度短的话就进入无网络页面
           }else if(Number(routeNetwork)<Number(pages.length)||!routeNetwork){
             // 先删除页面栈长度在存储最新页面栈长度
             uni.removeStorageSync('routeNetwork')
             uni.setStorageSync('routeNetwork',pages.length)
             // 判断当前页是否是tabber页 是就是保存当前页跳转 否就是删除当前页进入下一页
             if(tabberRoute.join(',').indexOf(to.path)!=-1){
               // 存储tabber页的路径
             uni.setStorageSync('routeTabber',to.path)
             // 保留当前页进入网络崩溃页
               uni.navigateTo({
                 url:'/standard/netNetwork/netNetwork'
               })  
             }else{
               // 删除当前页面进入网络崩溃页
               uni.redirectTo({
                 url:'/standard/netNetwork/netNetwork'
               })   
             }
             // 清除赋值给getNetworkType_time的定时器
             clearTimeout(getNetworkType_time)
           }else{
             // 更新页面栈长度
              uni.setStorageSync('routeNetwork',pages.length)
              // 执行赋值给timer的定时器前先销毁timer定时器 然后执行定时器
              clearTimeout(timer)
              timer = setTimeout(()=>{
                // 删除本地缓存configRoue后清除赋值给timer的定时器和清除赋值给getNetworkType_time的定时器
                uni.removeStorageSync('configRoue')
                clearTimeout(timer)
                clearTimeout(getNetworkType_time)
              },3000)
           }
         },100)
      statPvFlag = false
      }else{
         // 执行赋值给netNetworkFlag_time的定时器前先销毁netNetworkFlag_time定时器 然后在执行定时器
        clearTimeout(netNetworkFlag_time)
        netNetworkFlag_time = setTimeout(()=>{
          // 判断是否是在网络崩溃页时点击刷新功能的
          if(uni.getStorageSync('netNetworkFlag')){
            // 是的话删除判断是否是在网络崩溃页时点击刷新功能的本地缓存标识netNetworkFlag和删除页面栈长度后进入保存的上个页面
            uni.removeStorageSync('netNetworkFlag')
            uni.removeStorageSync('routeNetwork')
            uni.redirectTo({
              url:uni.getStorageSync('netNetwork')
            })
          }
          // 执行完销毁定时器
          clearTimeout(netNetworkFlag_time)
        })
      }

  	}
  });
  //#endif
	if (!statPvFlag) {
		//不需要pv类型的统计
		updateStatCommonProperty({
			pageUrl: url + to.path,
			referrerPageUrl: url + from.path
		});
	} else {
		setTimeout(() => {
			//#ifdef MP-WEIXIN
			if (to.path !== '/pages/index/index') {
				sldStatEvent({
					behaviorType: 'pv',
					pageUrl: url + to.path,
					referrerPageUrl: url + from.path
				});
			}
			//#endif
			//#ifndef MP-WEIXIN
			sldStatEvent({
				behaviorType: 'pv',
				pageUrl: url + to.path,
				referrerPageUrl: url + from.path
			});
			//#endif
		}, 3000)
	}
    

	if (isWeiXinBrower()) {
		let shareData = {
			title: document.title,
			desc: document.title,
			link: window.location.href,
			imgUrl: '',
		}

		WXBrowserShareThen(1, shareData);
		WXBrowserShareThen(2, shareData);
	}
})
export default router;
